package br.com.ged.infraestrutura;

import java.util.Date;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class PersistenceContextSingleton {
	public static final boolean DEBUG = true;
	private static final PersistenceContextSingleton singleton = new PersistenceContextSingleton();
	protected EntityManagerFactory emf;
	
	public static PersistenceContextSingleton getInstance(){
		return singleton;
	}
	
	/**
	 * Construtor protegido
	 */
	private PersistenceContextSingleton(){}
	
	/**
	 * Fornece EntityManagerFactory para a aplicação
	 * @return emf
	 */
	public EntityManagerFactory getEntityManagerFactory(){
		if(emf == null){
			criaEntityManagerFactory();
		}
		return emf;
	}
	
	/**
	 * Cria objeto do tipo EntityManagerFactory
	 */
	protected void criaEntityManagerFactory(){
		String persistenceUnitName = "ged";
		this.emf = Persistence.createEntityManagerFactory(persistenceUnitName);
		if(DEBUG){
			System.out.println("Contexto de persistência inicializado em: "
					+ new Date());
		}
	}
	
	/**
	 * Libera recursos
	 */
	public void fechaEntityManagerFactory(){
		if(emf != null){
			emf.close();
			emf = null;
			if(DEBUG){
				System.out.println("Contexto de persistência finalizado em: "
						+ new Date());
			}
		}
	}
}
